<template>
  <cu-layout :bgStyle="{ title: '我的优惠券' }" :navProp="{ placeholder: true }">
    <view :class="[`${prefixCls}-coupon-container`]">
      <view class="data-container">
        <view v-if="couponList.length == 0" class="no-data">
          <cu-empty mode="coupon"> </cu-empty>
        </view>
        <view v-else class="data-warp">
          <uv-checkbox-group v-model="radiovalue" placement="column" shape="circle">
            <view v-for="(item, index) in couponList" :key="index" @click="handleSelectCoupon(item)">
              <view :class="['coupon-item', { stacking: item.stack_enable === '1' }]">
                <uv-checkbox
                  :customStyle="{ position: 'absolute', right: '20px', top: '30px' }"
                  activeColor="#046f7e"
                  :disabled="item.custom_stack_enable"
                  :name="item.id"
                ></uv-checkbox>
                <view class="opacity-0"></view>
                <view class="coupon">
                  <view class="unit">￥</view>
                  <view class="price">{{ item.amout }}</view>
                  <view class="text">优惠券</view>
                </view>
                <view class="coupon-date">有效期 {{ splitTime(item.valid_start) }}-{{ splitTime(item.valid_end) }}</view>
                <view class="coupon-line"> </view>
                <view class="coupon-desc" @click.stop="handleOpen(item)">
                  <view :class="['fee_remark', { openBtn: item.openBtn }]">
                    {{ item.fee_scope_text }}
                  </view>
                  <uv-icon :name="item.openBtn ? 'arrow-up' : 'arrow-down'" :color="theme" size="12"></uv-icon>
                  <view v-if="item.openBtn" class="fee_scope_text">使用范围：{{ item.scope_detail || '-' }}</view>
                  <view v-if="item.openBtn" class="fee_scope_text">使用说明：{{ item.instructions || '-' }}</view>
                </view>
              </view>
              <view v-if="item.reason" class="coupon-reason">{{ item.reason }}</view>
            </view>
          </uv-checkbox-group>
          <view v-if="!showDisabled" class="disabled-coupon" @click="showDisabled = true">不可使用的优惠券 <uv-icon size="14px" color="#999999" name="arrow-down"></uv-icon></view>
          <!-- 不可使用优惠券展示列表 -->
          <template v-if="showDisabled">
            <view :class="['coupon-item disabled', { stacking: item.stack_enable === '1' }]" v-for="(item, index) in disabledList" :key="index">
              <view class="opacity-0"></view>
              <view class="coupon">
                <view class="unit">￥</view>
                <view class="price">{{ item.amout }}</view>
                <view class="text">优惠券</view>
              </view>
              <view class="coupon-date">有效期 {{ splitTime(item.valid_start) }}-{{ splitTime(item.valid_end) }}</view>
              <view class="coupon-line"> </view>
              <view class="coupon-desc" @click.stop="handleOpen(item)">
                <view :class="['fee_remark', { openBtn: item.openBtn }]">
                  {{ item.fee_scope_text }}
                </view>
                <uv-icon :name="item.openBtn ? 'arrow-up' : 'arrow-down'" :color="theme" size="12"></uv-icon>
                <view v-if="item.openBtn" class="fee_scope_text">使用范围：{{ item.scope_detail || '-' }}</view>
                <view v-if="item.openBtn" class="fee_scope_text">使用说明：{{ item.instructions || '-' }}</view>
              </view>
            </view>
          </template>
        </view>
      </view>
      <view class="fixed-wrap">
        <view class="fixed-button">
          <view class="pay-detail">
            <text class="desc">已抵扣{{ feeName }}：</text>
            <text class="unit">￥</text>
            <text class="pay">{{ amout }} </text>
          </view>
          <view class="submit" @click="handleUseCoupons">确认使用</view>
        </view>
        <uv-safe-bottom></uv-safe-bottom>
      </view>
      <uv-modal
        ref="coupon-modal"
        :showCancelButton="true"
        :title="`确认使用${radiovalue.length}张优惠券进行支付吗?`"
        content="若选择的优惠券未抵扣账单，使用后无法返还"
        @confirm="couponConfirm"
      ></uv-modal>
    </view>
  </cu-layout>
</template>

<script>
import { mapActions, mapGetters } from 'vuex'
import { customerData, payCouponPrice } from './api'
export default {
  name: 'coupon',
  components: {},
  mixins: [],
  props: {},
  data() {
    return {
      feeName: '费用',
      amout: '0.0',
      couponList: [],
      disabledList: [],
      pageConfig: {
        p: 1,
        ps: 10,
        totalCount: 0,
      },
      radiovalue: [],
      coupon_id: '',
      showDisabled: false, // 隐藏不可使用优惠券列表
    }
  },
  // 侦听属性
  watch: {},
  // 计算属性
  computed: {
    ...mapGetters(['theme']),
  },
  // 监听页面加载，该钩子被调用时data,computed,function,watch,props,slots已设置完成
  onLoad(options) {
    this.getData()
  },
  // 监听页面显示，页面每次出现在屏幕上都触发
  onShow() {},
  // 监听页面初次渲染完成，此时组件已挂载完成
  onReady() {},
  // 下拉刷新
  onPullDownRefresh() {
    this.getData()
  },
  // 加载更多
  onReachBottom() {
    if (this.pageConfig.totalCount > this.couponList.length) {
      this.pageConfig.p++
      this.getData()
    }
  },

  created() {},
  mounted() {},
  destroyed() {},
  methods: {
    ...mapActions([]),
    handleOpen(item) {
      item.openBtn = !item.openBtn
    },
    splitTime(time) {
      if (!time) return '-'
      return time.split(' ')[0]
    },
    async handleSelectCoupon({ id, amout, coupon_id, stack_enable, multi_enable, custom_stack_enable }) {
      if (custom_stack_enable) return // 如果点击当前优惠券是禁用属性 直接return
      // 只记录第一张优惠券的coupon_id 类型id
      if (this.coupon_id === '') {
        this.coupon_id = coupon_id
      }
      // 如果当前选择的优惠券id 等于点击的第2+张优惠券，则进行如下判断
      // 如果当前已选择再次点击 则删除选中的优惠券，
      // 如果只选中了一张优惠券则取消所有不可选中，
      // 如果当前已选中了多张，则只取消当前选中的这张优惠券
      if (this.radiovalue.includes(id)) {
        this.radiovalue.forEach((v, i) => {
          if (v == id) {
            this.radiovalue.splice(i, 1)
            if (this.radiovalue.length === 0) {
              this.couponList.forEach((v) => {
                v.custom_stack_enable = false
                v.reason = ''
              })
              this.coupon_id = ''
            } else {
              this.couponList.forEach((v) => {
                if (v.coupon_id === coupon_id) {
                  v.custom_stack_enable = false
                  v.reason = ''
                }
              })
            }
          }
        })
      } else {
        this.radiovalue.push(id)
        this.couponList.forEach((v) => {
          if (v.multi_enable === '0' && stack_enable === '0') {
            if (v.id !== id) {
              v.custom_stack_enable = true
            }
          } else if (v.multi_enable === '0' && stack_enable === '1') {
            if ((v.id !== id && v.stack_enable !== '1') || (v.id !== id && v.coupon_id === coupon_id)) {
              v.custom_stack_enable = true
            }
          } else if (v.multi_enable === '1' && stack_enable === '1') {
            if (v.stack_enable !== '1') {
              v.custom_stack_enable = true
            }
          } else if (v.multi_enable === '1' && stack_enable === '0') {
            if (v.coupon_id !== coupon_id) {
              v.custom_stack_enable = true
            }
          }
          // 控制不可使用优惠券的提示
          if (v.custom_stack_enable) {
            if (v.multi_enable === '0' && v.stack_enable === '0') {
              if (v.coupon_id === coupon_id) {
                v.reason = '该优惠券只可使用1张。'
              } else {
                v.reason = '当前不可叠加使用。'
              }
            } else if (v.multi_enable === '0' && v.stack_enable === '1') {
              if (v.coupon_id === coupon_id) {
                v.reason = '该优惠券只可使用1张。'
              } else {
                v.reason = '当前不可叠加使用。'
              }
            } else if (v.multi_enable === '1' && v.stack_enable === '1') {
              v.reason = '当前不可叠加使用。'
            } else if (v.multi_enable === '1' && v.stack_enable === '0') {
              v.reason = '当前不可叠加使用。'
            }
          }
        })
      }
      const { contract_id, belong_type } = this.$Route.query
      const couponIds = this.radiovalue
      if (couponIds.length === 0) {
        this.feeName = '费用'
        this.amout = '0.00'
        return
      }
      const { data } = await payCouponPrice({ contractId: contract_id, belong_type, couponIds })
      const { feeName, couponAmount } = data
      this.feeName = feeName
      this.amout = couponAmount || '0.00'
    },
    // 确认使用优惠券
    handleUseCoupons() {
      if (this.radiovalue.length === 0) return
      this.$refs['coupon-modal'].open()
    },
    couponConfirm() {
      const couponIds = this.radiovalue
      const discountAmount = this.amout
      const couponId = []
      this.couponList.forEach((item) => {
        if (this.radiovalue.includes(item.id)) {
          couponId.push(item.coupon_id)
        }
      })
      // 重定向跳转
      // uni.redirectTo({ url: '/pages/subpackage/bill/need-pay-details' })
      this.$ROUTE.go('/pages/subpackage/bill/need-pay-details', { ...this.$Route.query, couponIds, couponId, discountAmount })
    },
    // 解决请求第二页时，状态未绑定成功
    isDisabled(coupon_id) {
      if (this.coupon_id === '') return false
      if (this.coupon_id === coupon_id) return false
      return true
    },
    async getData() {
      const { contract_id, belong_type, couponIds, discountAmount } = this.$Route.query
      const { data } = await customerData({ contract_id, belong_type })
      uni.stopPullDownRefresh()
      this.couponList = data?.usable?.list || []
      this.disabledList = data?.disabled?.list || []
      this.radiovalue = couponIds ? couponIds.split(',') : []
      this.amout = discountAmount || '0.00'
    },
  },
}
</script>

<style lang="scss" scoped>
.#{prefixCls('coupon-container')} {
  position: relative;
  padding: 0 15px;
  overflow: hidden;
  box-sizing: border-box;
  // background: white;
  .data-container {
    padding-bottom: 100px;
    .data-warp {
      // overflow: hidden;
      padding-bottom: 20px;
      .coupon-item {
        position: relative;
        // overflow-y: clip;
        .poisition-checkbox {
          position: absolute;
          right: 20px;
          top: 30px;
        }
        .opacity-0 {
          background: white;
          opacity: 0;
          width: 100px;
          height: 100px;
          right: 10px;
          top: 0;
          position: absolute;
        }
        &::after {
          position: absolute;
          font-size: 12px;
          background: #ecf5f8;
          width: 46px;
          height: 46px;
          text-align: center;
          line-height: 20px;
          right: 0;
          top: 0;
        }
        margin-top: 12px;
        border: 1px solid $uv-primary;
        padding: 16px 0 0px 0px;
        border-radius: 8px;

        .coupon {
          display: flex;
          align-items: flex-end;
          padding-left: 12px;
          padding-right: 12px;
          .unit {
            font-size: 20rpx;
            color: $uv-primary;
          }
          .price {
            font-size: 60rpx;
            line-height: 60rpx;
            color: $uv-primary;
          }
          .text {
            margin-left: 8px;
            font-weight: 500;
            font-size: 14px;
            color: #333333;
          }
        }
        .coupon-date {
          padding-left: 12px;
          padding-right: 12px;
          padding-top: 12px;
          padding-bottom: 15px;
          font-weight: 400;
          font-size: 12px;
        }
        .coupon-line {
          padding-left: 12px;
          padding-right: 12px;
          width: calc(100% - 24px);
          height: 1px;
          border-bottom: 1px dashed $uv-primary;
          position: relative;
          &::before {
            content: ' ';
            position: absolute;
            width: 8px;
            height: 16px;
            left: -11px;
            border: 1px solid $uv-primary;
            transform: translate(0, -50%);
            border-radius: 50%;
            background: #f5f5f5;
            left: -1.5px;
            border-radius: 0 30px 30px 0; /* 右边圆角，左边直角 */
            border-color: $uv-primary;
            border-left-color: #f5f5f5;
          }
          &::after {
            content: ' ';
            position: absolute;
            width: 8px;
            height: 16px;
            border: 1px solid $uv-primary;
            transform: translate(0, -50%);
            border-radius: 50%;
            background: #f5f5f5;
            right: -1.5px;
            border-radius: 30px 0 0 30px; /* 右边圆角，左边直角 */
            border-color: $uv-primary;
            border-right-color: #f5f5f5;
          }
        }
        .coupon-desc {
          background: #ecf5f8;
          font-weight: 400;
          font-size: 10px;
          padding: 13px 12px;
          display: flex;
          justify-content: space-between;
          flex-wrap: wrap;
          border-radius: 8px;
          box-sizing: border-box;
          width: 100%;
          .fee_remark {
            width: calc(100% - 12px);
            white-space: nowrap;
            text-overflow: ellipsis;
            overflow: hidden;
          }
          .openBtn {
            width: calc(100% - 18px);
            white-space: unset;
          }
          .fee_scope_text {
            flex-basis: 100%;
            margin-top: 10px;
            line-height: 15px;
          }
        }
      }
      .coupon-reason {
        background: #046f7e;
        border-radius: 5px;
        font-size: 12px;
        padding: 5px 0px 5px 10px;
        color: #f5f5f5;
      }
      .disabled {
        filter: grayscale(100%);
      }
      .stacking {
        &::after {
          // content: '可使用';
          content: ' ';
          // background: #edf5f9;
          background: cdn('/common/static/images/icon/stacking.png');
          background-repeat: no-repeat;
          background-size: cover;
          background-position: center;
          // color: $uv-primary;
        }
      }
      .disabled-coupon {
        display: flex;
        justify-content: center;
        margin: 10px 0;
        padding: 10px 0;
        background: #f1f1f1;
        border-radius: 8px;
        font-size: 12px;
        color: #999999;
      }
    }
  }
  .fixed-wrap {
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 2;
    width: 100%;
    background: white;
    // background: linear-gradient(to bottom, white, #f5f5f5);
    // padding: 10rpx 0 0 20rpx;
    box-sizing: border-box;
    border-top: 1px solid #f1f1f1;
    .fixed-button {
      display: flex;
      .pay-detail {
        display: flex;
        align-items: center;
        width: 70%;
        color: #333333;
        .desc {
          padding-left: 10px;
          font-size: 10px;
          line-height: 20px;
          padding-top: 5px;
        }
        .unit {
          color: $uv-primary;
        }
        .pay {
          color: $uv-primary;
          font-size: 18px;
          line-height: 20px;
          font-weight: bold;
        }
      }
      .submit {
        flex: 1;
        margin: 10px;
        padding: 10px 15px;
        border-radius: 5px;
        background: $uv-primary;
        font-weight: bold;
        color: white;
        text-align: center;
      }
      ::v-deep .uv-button-wrapper {
        flex: 1;
        margin: 0 15px;
      }
    }
  }
}
</style>
